//如果使用CDN，则要开启下方import
// import Vue from 'vue'
// import VueRouter from 'vue-router'
// import NProgress from 'nprogress'
// import 'nprogress/nprogress.css'
import store from './store.js'
Vue.use(VueRouter)
import {
    getToken,
    getCookie,
    removeToken
} from '@/utils/cookie'

import {
    Message
} from 'element-ui'
let router = new VueRouter({
    mode: 'history',
    routes: [{
            path: "/",
            name: "entry",
            redirect: "index",
            component: () => import("./Entry.vue"),
            children: [{
                path: "/index",
                name: "index",
                component: () => import("./components/Index.vue"),
                children: [{
                    path: "/caryard",
                    name: "caryard",
                    component: () => import("./components/Caryard.vue")
                }, {
                    path: "/log",
                    name: "log",
                    component: () => import("./components/Log.vue")
                }]
            }, {
                path: '/login',
                name: 'login',
                component: () => import("./components/Login.vue"),
            }, ]
        },
        {
            path: '*',
            name: '404',
            component: () => import("./components/404.vue"),
        }
    ]
})

router.beforeEach((to, from, next) => {
    NProgress.start()
    var token = getToken();
    if (token) {
        if (to.path === '/login') {
            Message({
                message: '您已登录',
                type: 'error',
                duration: 1500
            })
            setTimeout(function() {
                // router.go(-1)
                // console.log(from)
                if (from.path == '/index') {
                    NProgress.done()
                    return false;
                } else {
                    router.push({
                        path: "/index"
                    })
                }
                next(false)
            }, 50)
        } else {
            //存在token 获取用户信息 如果获取到 next()
            //若果获取不到 则删除token
            // console.log(to)
            // console.log(from)
            // if (to.path == '/') {
            //     next();
            // } else {
            // console.log(store.state)
            // console.log(store.state.userinfo.username)
            if (store.state.userinfo.username == null) {
                store.dispatch("getUserInfo").then(res => {
                    next();
                }).catch(err => {
                    removeToken();
                    next();
                })
            } else {
                next();
            }
        }
    } else {
        if (to.path !== '/login') {
            router.push({
                path: '/login'
            })
            next(false)
        }
        next();
    }
})
router.afterEach((to, from) => {
    NProgress.done()
})

export default router;